package ca.uvic.cs.cogz.mapping.ui;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import ca.uvic.cs.cogz.mapping.filter.TreeFilterManager;
import ca.uvic.cs.cogz.mapping.ui.tree.MappingJTree;
import edu.stanford.smi.protege.model.KnowledgeBase;

/**
 * Class for applying search tree filters used by the MappingVisualizationPanel.
 * 
 * @author seanf
 */
public class SearchTextField extends JTextField {
	private static final long serialVersionUID = 5832853932891183662L;

	/** search text that is displayed before the user types */
	public static final String SEARCH_DEFAULT_TEXT_LABEL = "type filter text";

	private MappingVisualizationPanel mappingVisualizationPanel;
	private MappingJTree tree;
	private KnowledgeBase knowledgeBase;
	private int treeSearchType;

	public SearchTextField(MappingVisualizationPanel mappingVisualizationPanel, MappingJTree tree, KnowledgeBase knowledgeBase, int treeSearchType) {
		super(SEARCH_DEFAULT_TEXT_LABEL);

		this.mappingVisualizationPanel = mappingVisualizationPanel;
		this.tree = tree;
		this.knowledgeBase = knowledgeBase;
		this.treeSearchType = treeSearchType;
		
		tree.addResetListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				setText(SEARCH_DEFAULT_TEXT_LABEL);
			}
		});

		addFocusListener(getSearchFocusListener());
		addKeyListener(getSearchKeyAdapter());
	}

	private KeyAdapter getSearchKeyAdapter() {
		return new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				TreeFilterManager.getInstance().setActiveSearch(treeSearchType);
				mappingVisualizationPanel.performSearch(SearchTextField.this.getText(), (MappingJTree) tree, knowledgeBase);
			}
		};
	}

	/**
	 * Creates a focus listener for the text boxes to remove the default search text on focus and
	 * add it back in if nothing has been searched and focus has been lost.
	 */
	private FocusListener getSearchFocusListener() {
		return new FocusListener() {
			public void focusGained(FocusEvent e) {
				if (SearchTextField.this.getText().equals(SEARCH_DEFAULT_TEXT_LABEL)) {
					SearchTextField.this.setText("");
				}
			}

			public void focusLost(FocusEvent e) {
				if (SearchTextField.this.getText().length() == 0) {
					SearchTextField.this.setText(SEARCH_DEFAULT_TEXT_LABEL);
				}
			}
		};
	}
}
